// 引入 node_modules
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


// 引入路由
var mainRouter = require('./routes/main.router')

var app = express();

// 设置 view engine (使用 ejs)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


// ↓--通用路由--↓ //
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'node_modules')));
// ↑--通用路由--↑ //

// 主路由
app.use(mainRouter)

// ↓--错误处理路由--↓ //
// ! 捕获404错误并交给错误处理程序
app.use(function (req, res, next) {
  next(createError(404));
});
// 错误处理程序
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  console.error(err)
  res.end(err);
});
// ↑-错误处理路由--↑ //

module.exports = app;
